package tv.huan.media.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tv.huan.media.domain.Album;
import tv.huan.media.mapper.AlbumMapper;
import tv.huan.media.rabbit.RabbitConstant;
import tv.huan.media.util.MailInfoUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 版权到期提醒
 * 
 * @author ruoyi
 */
@Component("copyrightWarnTask")
public class CopyrightWarnTask
{
    private static final Log logger = LogFactory.getLog(CopyrightWarnTask.class);

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    @Value("${huan.copyrightwarn}")
    private int warnDays;

    public void execute() {
        logger.info("媒资版权任务开始，提前提醒天数：" + warnDays);
        Date today = new Date();
        String warmDate = getEndDate(today,warnDays);
        List<Album> albumList = albumMapper.selectAlbumByAuthorEndDate(warmDate);
        String subject = "媒资版权到期提醒";
        String text = "<h5>请大家注意：" +
                         "<br />\n" +
                         "以下内容" + warnDays + "天之后版权到期，请对接人及时续约，或通知驻地下线处理。" +
                         "<br />\n" +
                         "<br/>提醒片单如下：\n</h5>";
        if (null != albumList && albumList.size() > 0){
            String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.COPYRIGHT_WARN,albumList);
            rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
        }
    }

    /**
     * 将日期加天数得到新日期
     * @param date 字符串yyyy-MM-dd HH:mm:ss
     * @return date
     */
    public static String getEndDate(Date date, int count){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, count);
        return format.format(calendar.getTime());
    }

    public static void main(String[] args) {
        System.out.println(getEndDate(new Date(),15));
    }
}
